var mongoose = require('./db.js')
var Schema = mongoose.Schema
var CodeSchema = new Schema({
  title: { type: String }, //代码标题
  sign: { type: String }, //代码签名
  type: { type: String }, //代码类型
  introduce: { type: String }, //代码介绍
  option: {type: Array }, //代码字段介绍
  code: {type: String } //代码
})
var Code = mongoose.model('CodeChunk', CodeSchema)

function saveCode(data) {
  var codeData = new Code({
    title: data.title,
    sign: data.sign,
    type: data.type,
    introduce: data.introduce,
    option: data.option,
    code: data.code
  })
  var callbackObj = new Promise(function(resolve, reject) {
    codeData.save(function(err, res) {
      if (err) {
        console.log(reject, '数据库错误')
        reject(err)
      } else {
        console.log(resolve, '操作成功')
        resolve(res)
      }
    })
  })
  return callbackObj;
}

function findCode() {
  var callbackObj = new Promise(function(resolve, reject) {
    Code.find({},function(err, res) {
      if (err) {
        console.log(reject, '数据库错误')
        reject(err)
      } else {
        console.log(resolve, '操作成功')
        resolve(res)
      }
    }).sort({type: 'asc'})
  })
  return callbackObj;
}

function findByIdAndUpdate(id,data) {
  var callbackObj = new Promise(function(resolve, reject) {
    Code.findByIdAndUpdate(id, data, function(err, res) {
      if (err) {
        console.log(reject, '数据库错误')
        reject(err)
      } else {
        console.log(resolve, '操作成功')
        resolve(res)
      }
    })
  })
  return callbackObj;
}

function findByIdAndRemove(id) {
  var callbackObj = new Promise(function(resolve, reject) {
    Code.findByIdAndRemove(id, function(err, res) {
      if (err) {
        console.log(reject, '数据库错误')
        reject(err)
      } else {
        console.log(resolve, '操作成功')
        resolve(res)
      }
    })
  })
  return callbackObj;
}

module.exports = {
  saveCode: saveCode,
  findCode: findCode,
  updateCode: findByIdAndUpdate,
  deleteCode: findByIdAndRemove
}